package com.woniu.defecttracking.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.defecttracking.commens.Result;
import com.woniu.defecttracking.entity.AccountDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        AccountDetails accountDetails = (AccountDetails) authentication.getPrincipal();

        Result result = Result.getInstance(accountDetails).setMessage("登录成功");

        String resp = objectMapper.writeValueAsString(result);

        response.getWriter().write(resp);
        response.getWriter().flush();
    }
}
